/**
 * 
 */
package org.pump.client.codec;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

import org.apache.mina.core.buffer.IoBuffer;
import org.pump.client.type.LengthCodedBinary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liudong03
 *
 */
public class ErrorPack extends ResultPack{
	private static final Logger mylog = LoggerFactory.getLogger(ErrorPack.class);
	int errno;
	byte marker;
	byte[] sqlstate = new byte[5];
	String message;

	
	public static ErrorPack readBuffer(IoBuffer in,int len)
	{
		if(in.remaining() < len)
		{
			return null;
		}
		ErrorPack errorpack = new ErrorPack();
		errorpack.errno = in.getUnsignedShort();
		errorpack.len += 2;
		errorpack.marker = in.get();
		errorpack.len += 1;
		in.get(errorpack.sqlstate);
		errorpack.len += errorpack.sqlstate.length;
		
		int msglen = len - errorpack.len;
		if(msglen > 0)
		{
			byte[] temp = new byte[msglen];
			in.get(temp);
			try {
				errorpack.message = new String(temp,"US-ASCII");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				mylog.error("encoding message fail",e);
				return null;
			}
			errorpack.len += msglen;
		}
		return errorpack;
	}
	/**
	 * 
	 */
	public ErrorPack() {
		// TODO Auto-generated constructor stub
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "\nerrno=[" + this.errno + "]\nerror message=[" + this.message + "]";
	}
	
	
}
